package com.ruoyi.consumer.controller;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.consumer.constance.AgentPoxyLevelEnum;
import com.ruoyi.consumer.controller.wallet.WalletServiceImpl;
import com.ruoyi.consumer.domain.*;
import com.ruoyi.consumer.service.impl.*;
import com.ruoyi.consumer.utils.pay.HttpClient;
import com.ruoyi.consumer.utils.pay.HttpRequest;
import com.ruoyi.system.service.impl.SysDeptServiceImpl;
import com.ruoyi.web.controller.tool.QRTool;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.ruoyi.consumer.utils.PictureConverter.convertStringToJsonArray;
import static com.ruoyi.framework.datasource.DynamicDataSourceContextHolder.log;


/**
 * @author: lizhouwei
 * @ date : 2023/9/27
 * @description:
 */
@Api(tags = "用户账号")
@RestController
@RequestMapping("/api/user")
public class UserController {

    @Autowired
    private WxConfig wxConfig;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private CCarServiceImpl carService;

    @Autowired
    private CUserServiceImpl userService;

    @Autowired
    private CCompanyServiceImpl companyService;

    @Autowired
    private CWalletPersonServiceImpl walletPersonService;

    @Autowired
    private WalletServiceImpl walletService;

    @Autowired
    private SysDeptServiceImpl sysDeptService;

    @Autowired
    private QRTool qrTool;

    @Autowired
    private CAgentRelationsServiceImpl agentRelationsService;

    @ApiOperation("根据code获取openid")
    @GetMapping("/getMyOpenid")
    public AjaxResult getMyOpenid(@ApiParam(value = "wx.login返回的code", required = true) String code) {
        String grant_type = "authorization_code";
        String params = "appid=" + wxConfig.getAppid() + "&secret=" + wxConfig.getAppSecret() + "&js_code=" + code + "&grant_type=" + grant_type;
        String sr = HttpRequest.sendPost("https://api.weixin.qq.com/sns/jscode2session", params);
        JSONObject json = JSONObject.parseObject(sr);
        System.out.println("解析code请求结果:" + json.toString());
        String openid = json.getString("openid");
        AjaxResult ajaxResult = new AjaxResult();
        ajaxResult.put("openid", openid);
        return ajaxResult;
    }

    @ApiOperation("解密code获取手机号")
    @GetMapping("/getMyPhone")
    public AjaxResult getMyPhone(@ApiParam(value = "此处是button获取的code，而不是wx.login的", required = true) String code) {
        String url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" + redisCache.getCacheObject("token:" + "findConsumerAccessToken");
        System.out.println("access_token" + url);
        // 请求参数
        Map<String, String> map = new HashMap<>(1);
        map.put("code", code);

        // 发起请求 注意请求参数map要转成json字符串
        String res = HttpClient.postJson(url, JSON.toJSONString(map), null);

        // 解析请求结果 拿到手机号
        JSONObject jsonObject = JSONObject.parseObject(res);
        String phone_info = jsonObject.get("phone_info").toString();
        JSONObject jsonPhone_info = JSONObject.parseObject(phone_info);
        String phoneNumber = jsonPhone_info.get("phoneNumber").toString();

        System.out.println("用户手机号：" + phoneNumber);
        AjaxResult ajaxResult = new AjaxResult();
        ajaxResult.put("phoneNumber", phoneNumber);
        return ajaxResult;
    }

    @ApiOperation("注册新用户")
    @GetMapping("/loginNewUser")
    public AjaxResult loginNewUser(@ApiParam(value = "openid", required = true) String userOpenid,
                                   @ApiParam(value = "用户头像", required = true) String userHead,
                                   @ApiParam(value = "用户昵称", required = true) String userNick,
                                   @ApiParam(value = "用户手机号", required = true) String userPhone,
                                   @ApiParam(value = "邀请码", required = false) Integer agentId) {
        log.info("==================================注册新用户=========================================");
        AjaxResult ajaxResult = new AjaxResult();
        CUser users = new CUser();
        users.setOpenid(userOpenid);
        log.info("==================================判断用户是否已经注册过=========================================", users);
        //判断用户是否已经注册过
        List<CUser> usersList = userService.selectCUserList(users);
        if (usersList.size() > 0) {
            return ajaxResult.put("msg", "该用户已注册过，请勿重复注册");
        }
        log.info("==================================插入新用户=========================================");
        CUser user = new CUser();
        user.setOpenid(userOpenid);
        user.setUserHeader(userHead);
        user.setUserNick(userNick);
        user.setUserPhone(userPhone);
        user.setUserRole(0);
        userService.insertCUser(user);
        log.info("==================================插入新用户结束=========================================", user);
        if (agentId != null) {
            log.info("==================================进入插入代理=========================================", agentId);
            CAgentRelations cAgentRelations = agentRelationsService.selectCAgentRelationsByAgentId(agentId);
            Assert.notNull(cAgentRelations, "邀请码不存在");
            CAgentRelations agent = new CAgentRelations();
            agent.setSuperUserId(cAgentRelations.getUserId());
            agent.setUserId(user.getUserId());
            agent.setAgentPath(cAgentRelations.getAgentPath() + "," + user.getUserId());
            agent.setAgentLevel(AgentPoxyLevelEnum.NEW_USER.getDescription());
            agentRelationsService.insertCAgentRelations(agent);
            log.info("==================================插入代理结束=========================================", cAgentRelations);
        }
        log.info("==================================创建钱包=========================================");
        //创建钱包
        int i = createWallet(user.getUserId());
        Assert.isTrue(i > 0, "创建钱包失败");
        ajaxResult.put("msg", "注册成功");
        ajaxResult.put("data", user);
        log.info("==================================创建钱包结束=========================================");
        log.info("==================================注册新用户结束=========================================");
        return ajaxResult;
    }

    //创建钱包
    public int createWallet(Integer userId) {
        CWalletPerson cWalletPerson = new CWalletPerson();
        cWalletPerson.setUserId(userId);
        cWalletPerson.setWalletFree(0L);
        //加密处理
        Map<String, Object> walletData = new HashMap<>();
        walletData.put("user_uuid", userId);
        walletData.put("wallet_income", 0L);
        walletData.put("wallet_outcome", 0L);
        walletData.put("balance_fee", 0L);
        // 你的密钥
        String walletCheckKey = wxConfig.getWalletCheckKey();
        // 生成签名
        String checkSign = walletService.encodeHMAC(walletData, walletCheckKey);
        cWalletPerson.setWalletSign(checkSign);
        return walletPersonService.insertCWalletPerson(cWalletPerson);
    }

    @ApiOperation("根据openid判断用户注册")
    @GetMapping("/login")
    public AjaxResult login(@ApiParam(value = "openid", required = true) String userOpenid) {
        AjaxResult ajaxResult = new AjaxResult();
        CUser users = new CUser();
        users.setOpenid(userOpenid);
        List<CUser> usersList = userService.selectCUserList(users);
        if (usersList.size() > 0) {
            ajaxResult.put("msg", "该用户已存在");
            ajaxResult.put("data", usersList.get(0));
        } else {
            ajaxResult.put("msg", "该用户没有注册过");
        }
        return ajaxResult;
    }

    @ApiOperation("通过userid修改用户昵称头像")
    @GetMapping("/updataUserByUserId")
    public AjaxResult updataUserByUserId(@ApiParam(value = "userId", required = true) Integer userId,
                                         @ApiParam(value = "userNick", required = true) String userNick,
                                         @ApiParam(value = "UserName", required = true) String UserName,
                                         @ApiParam(value = "userHead", required = true) String userHead) {
        AjaxResult ajaxResult = new AjaxResult();
        CUser users = userService.selectCUserByUserId(userId);
        users.setUserHeader(userHead);
        users.setUserNick(userNick);
        users.setUserName(UserName);
        int i = userService.updateCUser(users);
        if (i > 0) {
            CUser users1 = userService.selectCUserByUserId(userId);
            ajaxResult.put("msg", "修改成功");
            ajaxResult.put("data", users1);
        } else {
            ajaxResult.put("msg", "服务器错误");
        }
        return ajaxResult;
    }


    /**
     * 通过userid获取用户信息
     *
     * @param userId
     * @return
     */
    @ApiOperation("通过userid获取用户信息")
    @GetMapping("/getUserInfo")
    public AjaxResult getUserInfo(@ApiParam(value = "userId", required = true) Integer userId) {
        AjaxResult ajaxResult = new AjaxResult();
        Map<String, Object> map = new HashMap<>();
        CUser users = userService.selectCUserByUserId(userId);
        Assert.notNull(users, "用户不存在");

        CAgentRelations agent = new CAgentRelations();
        agent.setUserId(userId);
        agent.setIsDelete(0);
        List<CAgentRelations> cAgentRelations = agentRelationsService.selectCAgentRelationsList(agent);
        if (!cAgentRelations.isEmpty()) {
            map.put("agentId", cAgentRelations.get(0).getAgentId());
            map.put("agentLevel", cAgentRelations.get(0).getAgentLevel());
        } else {
            map.put("agentId", "暂无代理信息");
        }

        if (users.getCompanyId() != 0) {
            CCompany cCompany = companyService.selectCCompanyByCompanyId(users.getCompanyId());
            if (cCompany.getCompanyLogo() != null) {
                String string = convertStringToJsonArray(cCompany.getCompanyLogo());
                //单独插入公司图片到cCompany
                cCompany.setCompanyLogo(string);
            }
            map.put("company", cCompany);
        } else {
            map.put("company", "暂无公司信息");
        }

        if (users.getCarId() != 0) {
            CCar cCar = carService.selectCCarByCarId(users.getCarId());
            map.put("car", cCar.getPlateNum());
        } else {
            map.put("car", "暂无车辆信息");
        }
        if (users == null) {
            ajaxResult.put("msg", "用户不存在");
        } else {
            map.put("user", users);
            ajaxResult.put("msg", "获取成功");
            ajaxResult.put("data", map);
        }
        return ajaxResult;
    }

    /**获取当前登陆用户的公司id*/
    @ApiOperation("获取当前登陆用户的公司id")
    @GetMapping("/getCompanyId")
    public AjaxResult getCompanyId(HttpServletRequest request) {
        Long deptId = SecurityUtils.getDeptId();
        SysDept dept = sysDeptService.selectDeptById(deptId);
        if (dept == null) {
            return AjaxResult.error("部门不存在");
        }
        if (dept.getParentId() == 100) {
            CCompany cCompany = new CCompany();
            cCompany.setCompanDept(Math.toIntExact(deptId));
            List<CCompany> cCompanyList = companyService.selectCCompanyList(cCompany);
            if (cCompanyList.size() == 0) {
                return AjaxResult.error("公司不存在");
            }
            return AjaxResult.success(cCompanyList.get(0).getCompanyId());
        } else {
            CCompany cCompany = new CCompany();
            cCompany.setCompanDept(Math.toIntExact(dept.getParentId()));
            List<CCompany> cCompanyList = companyService.selectCCompanyList(cCompany);
            if (cCompanyList.size() == 0) {
                return AjaxResult.error("公司不存在");
            }
            return AjaxResult.success(cCompanyList.get(0).getCompanyId());
        }
    }
}
